<template>
  <up-popup
    :show="rechargeMethodsShow"
    @close="rechargeMethodsShow = false"
    :round="20"
  >
    <view class="rechargeMethods">
      <view class="title"
        >請選擇充值方式 <i @tap="rechargeMethodsShow = false"></i
      ></view>
      <view class="rechargeList">
        <view
          v-for="(item, idx) in bankPaymentList"
          :key="idx"
          @tap="activeIdx = idx"
          :class="{ active: activeIdx == idx }"
        >
          <view> <image :src="item.icon" mode="scaleToFill" /> </view>
          <view>{{ item.payment_name }}</view>
        </view>
      </view>
      <up-button
        text="確認選擇"
        @tap="confirmSelection"
        type="primary"
      ></up-button>
    </view>
    <up-modal
      :show="amountShow"
      confirmText="确认"
      cancelText="取消"
      :title="bankPaymentObj.payment_name"
      :showCancelButton="true"
      @cancel="amountShow = false"
      @confirm="quickPaymentPlaceOrderFn"
    >
      <view class="thirdParty">
        <view>转账金额（最低：${{ bankPaymentObj.price_min }}）</view>
        <up-input
          placeholder="請輸入轉帳金额"
          border="surround"
          focus
          v-model="amount"
        ></up-input>
      </view>
    </up-modal>
  </up-popup>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance } from "vue";
const instance = getCurrentInstance()?.appContext.config.globalProperties;

import { BankPayment, QuickPaymentPlaceOrder } from "@/api/UserApi";
let rechargeMethodsShow = ref<boolean>(false);

let activeIdx = ref<number>(0);

const rechargeMethodsOpen = () => {
  rechargeMethodsShow.value = true;
};
let bankPaymentList = ref<Array<any>>([]);
const bankPaymentFn = async () => {
  bankPaymentList.value = await BankPayment();
};
let amount = ref<number | string>();
let amountShow = ref<boolean>(false);
let bankPaymentObj = ref<any>({});

const confirmSelection = async () => {
  let obj = bankPaymentList.value[activeIdx.value];
  bankPaymentObj.value = obj;
  console.log(obj);
  if (obj.card_number) {
    rechargeMethodsShow.value = false;
    instance?.goTo(
      "/pages/myWallet/transferSubmission?bankPaymentObj=" +
        encodeURIComponent(JSON.stringify(obj))
    );
  } else {
    amountShow.value = true;
  }
};

const quickPaymentPlaceOrderFn = async () => {
  if (bankPaymentObj.value.price_min > Number(amount.value || 0)) {
    uni.showToast({
      title: "最低充值$" + bankPaymentObj.value.price_min,
      icon: "none",
    });
    return;
  }
  let obj = await QuickPaymentPlaceOrder({
    amount: amount.value,
    payment_id: bankPaymentObj.value.payment_id,
  });
  amount.value = "";
  amountShow.value = false;
  rechargeMethodsShow.value = false;
  instance?.goTo("/pages/myWallet/webview?payUrl=" + obj.payUrl);
};

bankPaymentFn();
defineExpose({
  rechargeMethodsOpen,
});
</script>
<style scoped lang="scss">
@import "../../../static/scss/myWallet.scss";
</style>
